import axios from 'axios'
import qs from 'qs'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'

axios.defaults.baseURL = 'http://127.0.0.1:8080/'
axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded;charset=UTF-8'
// 在request 拦截器中塞入token
axios.interceptors.request.use(config => {
  if (store.state.token) config.headers['User-Token'] = store.state.token
  if (config.method === 'post') {
    config.data = qs.stringify(config.data)
  }
  return config
})
// response 拦截器中
axios.interceptors.response.use(config => {
  if (config.data.code === '100') {
    Message.error('登录超时')
    router.push('/login')
  }
  return config
})

export default axios
